package com.eln.medplayer;

import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Random;

import com.eln.medplayer.VidActivity.MyGestureDetector;
import com.eln.medplayer.VidActivity.MyGestureDetectorSound;
import com.eln.medplayer.VidActivity.MyGestureListener;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Bitmap.Config;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.provider.MediaStore;
import android.view.GestureDetector;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.View.OnTouchListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;

public class AudActivity extends Activity implements OnCompletionListener, SeekBar.OnSeekBarChangeListener{
	WakeLock wakeLock;
	private static final String[] EXTENSIONS = { ".mp3", ".mid", ".wav", ".ogg", ".mp4" }; //Playable Extensions
	//List<String> trackNames; //Playable Track Titles
	//List<String> trackArtworks; //Track artwork names
	AssetManager assets; //Assets (Compiled with APK)
	File path; //directory where music is loaded from on SD Card
	File path2; //directory where album artwork is loaded from on SD Card
	Music track; //currently loaded track
	ImageView bg; //Track artwork
	//Button btnPlay; //The play button will need to change from 'play' to 'pause', so we need an instance of it
	boolean isTuning; //is user currently jammin out, if so automatically start playing the next track
	int currentTrack; //index of current track selected
	int type; //0 for loading from assets, 1 for loading from SD card
	float currX=0;
	
	private static final String MEDIA_AUDIO_PATH = new String("/mnt/sdcard/audio");
	//private static final String MEDIA_ARTWORTKS_PATH = new String("/mnt/sdcard/audio");
	private ImageButton btnPlay;
	private ImageButton btnNext;
	private ImageButton btnPrevious;
	private ImageButton btnPlaylist;
	private ImageButton btnHome;
	private ImageButton btnSound;
	private SeekBar audioProgressBar;
	private TextView audioTitleLabel;
	private TextView audioCurrentDurationLabel;
	private TextView audioTotalDurationLabel;
    private Handler mHandler = new Handler();;
	private Utilities utils;
	private int seekForwardTime = 5000; // 5000 milliseconds
	private int seekBackwardTime = 5000; // 5000 milliseconds
	//private List<String> audiolist;
		private String current;
		private static Animation slideUpIn;
		private static Animation slideUpOut;
		private static Animation slideTopIn;
		private static Animation slideTopOut;
		private static View controlsView;
		private static View titleView;
		private static View mainView;
		private static View progressView;
		private static ImageView artworkView;
		static RelativeLayout progressLayout;
		private static int currentaudioIndex=0;
		private static int menuOption=0;
		private static int soundPos=0;
		private static int soundPosMax=0;
		private static int sp=0;
		private static ArrayList<Movie> movieList;
		private static  AudioManager mAudioManager;
		
		private static final int SWIPE_MIN_DISTANCE = 120;
	    private static final int SWIPE_MAX_OFF_PATH = 250;
	    private static final int SWIPE_THRESHOLD_VELOCITY = 200;
	    private GestureDetector gestureDetector;
	    protected MyGestureListener myGestureListener;
	    public static float startX=0;
	    public static float X0=0;
	    public static float XMax=0;
	
    @SuppressWarnings("unchecked")
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setVolumeControlStream(AudioManager.STREAM_MUSIC);
		PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
		wakeLock = powerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK, "Lexiconda");
        
		mAudioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
	    soundPos = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
	    soundPosMax=mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
	   // sp=soundPosMax/10*-1;
	    sp=soundPosMax/10;
	    
	    
		
        RelativeLayout relative = new RelativeLayout(this);
	    
	    mainView=View.inflate(getBaseContext(),R.layout.audio_player,null);
	    relative.addView(mainView);
	    
	    controlsView=View.inflate(getBaseContext(),R.layout.controls_vid,null);
        relative.addView(controlsView);
        controlsView.setVisibility(View.GONE);
        
        titleView=View.inflate(getBaseContext(),R.layout.title_vid,null);
        relative.addView(titleView);
        titleView.setVisibility(View.GONE);
        
        progressView = View.inflate(getBaseContext(),R.layout.progressbar, null);
        relative.addView(progressView);
        
	
       // setContentView(R.layout.audio_player);
	    setContentView(relative);
	    gestureDetector = new GestureDetector(new MyGestureDetector());
	    
	    artworkView = (ImageView) findViewById(R.id.bg);
	    
        myGestureListener = new MyGestureListener(this);
		
        artworkView.setOnTouchListener(myGestureListener);
	    
	   /*artworkView.setOnTouchListener(new View.OnTouchListener() {
            public boolean onTouch(View v, MotionEvent event) {
            	if (controlsView.getVisibility()==View.GONE){
                if (gestureDetector.onTouchEvent(event)) {
                    return true;
                }
            	}
                return false;
            }
        });*/
	    
	    progressLayout = (RelativeLayout) findViewById(R.id.progressLayout);
		progressLayout.setVisibility(View.VISIBLE);
	    
	    //controlsView.setVisibility(View.GONE);
		//titleView.setVisibility(View.GONE);
		
		 Intent i = getIntent();
		 currentaudioIndex = i.getExtras().getInt("listIndex");
		 menuOption = i.getExtras().getInt("menuOption");
		 //movieList=(ArrayList<Movie>)i.getExtras().getSerializable("movieList");
		
		  movieList=i.getParcelableArrayListExtra("movieList"); 
			
			
			
		   
			// All player buttons
			btnPlay = (ImageButton) findViewById(R.id.btnPlay);
			btnPlay.setImageResource(R.drawable.btn_pause);
			btnNext = (ImageButton) findViewById(R.id.btnNext);
			btnPrevious = (ImageButton) findViewById(R.id.btnPrevious);
			btnPlaylist = (ImageButton) findViewById(R.id.btnPlaylist);
			btnHome = (ImageButton) findViewById(R.id.btnHome);
			btnSound = (ImageButton) findViewById(R.id.btnSound);
			audioProgressBar = (SeekBar) findViewById(R.id.songProgressBar);
			audioTitleLabel = (TextView) findViewById(R.id.songTitle);
			audioCurrentDurationLabel = (TextView) findViewById(R.id.songCurrentDurationLabel);
			audioTotalDurationLabel = (TextView) findViewById(R.id.songTotalDurationLabel);
			
			setVolumeCtrl(getBaseContext(),btnSound,soundPos);
			
			// Listeners
			audioProgressBar.setOnSeekBarChangeListener(this); // Important
			
			//trackNames = new ArrayList<String>();
          	//trackArtworks = new ArrayList<String>();
          	assets = getAssets();
          	currentTrack = 0;
          	isTuning = false;
			this.type = 1;
			//addTracks(getTracks());
			track = loadMusic(1);
			track.mediaPlayer.setOnCompletionListener(this); // Important
			
			utils = new Utilities();
			
		    slideUpIn = AnimationUtils.loadAnimation(this, R.anim.slide_up);
	        slideUpOut = AnimationUtils.loadAnimation(this, R.anim.slide_down);
	        
	        slideTopIn = AnimationUtils.loadAnimation(this, R.anim.slide_top_down);
	        slideTopOut = AnimationUtils.loadAnimation(this, R.anim.slide_top_up);
			//mh=new MediaHelper();
			//mh.getaudioList();
			//File audpath = new File(MEDIA_AUDIO_PATH);
			//audiolist= new ArrayList<String>();
			//audiolist=Arrays.asList(audpath.list());//mh.audiols;
			
				
			 btnPlay.setOnClickListener(new View.OnClickListener() {
					
					@Override
					public void onClick(View arg0) {
					
						synchronized(this){
							if(track.mediaPlayer.isPlaying()){
								if(track.mediaPlayer!=null){
									track.mediaPlayer.pause();
									// Changing button image to play button
									btnPlay.setImageResource(R.drawable.btn_play);
								}
							}else{
								// Resume song
								if(track.mediaPlayer!=null){
									track.mediaPlayer.start();
									// Changing button image to pause button
									btnPlay.setImageResource(R.drawable.btn_pause);
								}
							}
						}
						
					}
				});
				
				
				/**
				 * Next button click event
				 * Plays next song by taking currentSongIndex + 1
				 * */
				btnNext.setOnClickListener(new View.OnClickListener() {
					
					@Override
					public void onClick(View arg0) {
						// check if next song is there or not
						if(currentaudioIndex < (movieList.size() - 1)){
							playaudio(currentaudioIndex + 1);
							currentaudioIndex = currentaudioIndex + 1;
						}else{
							// play first song
							playaudio(0);
							currentaudioIndex = 0;
						}
						
					}
				});
				
				/**
				 * Back button click event
				 * Plays previous song by currentSongIndex - 1
				 * */
				btnPrevious.setOnClickListener(new View.OnClickListener() {
					
					@Override
					public void onClick(View arg0) {
						if(currentaudioIndex > 0){
							playaudio(currentaudioIndex - 1);
							currentaudioIndex = currentaudioIndex - 1;
						}else{
							// play last song
							playaudio(movieList.size() - 1);
							currentaudioIndex = movieList.size() - 1;
						}
						
					}
				});
				
					
				/**
				 * Button Click event for Play list click event
				 * Launches list activity which displays list of songs
				 * */
				btnPlaylist.setOnClickListener(new View.OnClickListener() {
					
					@Override
					public void onClick(View arg0) {
						mHandler.removeCallbacks(mUpdateTimeTask);
						Intent i = new Intent(getApplicationContext(), VidList.class);
						i.putExtra("menuOption",menuOption);
						startActivity(i);
						AudActivity.this.overridePendingTransition(
								R.anim.slide_in_left, 
								R.anim.slide_out_right
					    		);
						finish();
					}
				});
				
	            btnHome.setOnClickListener(new View.OnClickListener() {
					
					@Override
					public void onClick(View arg0) {
						mHandler.removeCallbacks(mUpdateTimeTask);
						Intent i = new Intent(getApplicationContext(), MedPlayer.class);
						i.putExtra("menuOption",menuOption);
						startActivity(i);
						finish();
					}
				});
	            
	           /* btnSound.setOnClickListener(new View.OnClickListener() {
					
					@Override
					public void onClick(View arg0) {
					   if (soundPos+sp>soundPosMax){
					     sp=sp*-1;
					   }
					   if (soundPos+sp<0){
						 sp=sp*-1;  
					   }
					   setVolumeCtrl(getBaseContext(),btnSound);
					   soundPos=soundPos+sp;
					   mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, soundPos+sp, 0);
					}
	            });
	            
	            btnSound.setOnTouchListener(new View.OnTouchListener() {

	                @Override
	                public boolean onTouch(View v, MotionEvent event) {
	                    // TODO Auto-generated method stub
	                	if (event.getAction() == MotionEvent.ACTION_HOVER_MOVE) {
	                		event.getX();
	                        return true;
	                    } else if (event.getAction() == MotionEvent.ACTION_DOWN) {
	                       
	                        return true;
	                    } else if (event.getAction() == MotionEvent.ACTION_UP) {
	                       
	                        return true;
	                    } else if(event.getAction() == MotionEvent.ACTION_OUTSIDE)
	                    {

	                        // Do some stuffs here
	                    }

	                    return false;
	                }
	            }); */
	            
	           /* btnSound.setOnTouchListener(new View.OnTouchListener() {
		            public boolean onTouch(View v, MotionEvent event) {
		            	if (gestureDetectorSound.onTouchEvent(event)) {
		                    return true;
		                }
		                return false;
		            }
		        });*/
	            
	            btnSound.setOnTouchListener(new View.OnTouchListener() {

	                @Override
	                public boolean onTouch(View v, MotionEvent event) {
	                    // TODO Auto-generated method stub
	                	if (event.getAction() == MotionEvent.ACTION_HOVER_MOVE) {
	                		//event.getX();
	                        return true;
	                    } else if (event.getAction() == MotionEvent.ACTION_DOWN) {
	                       startX=event.getX();
	                       X0=btnSound.getX();
	                       XMax=btnSound.getX()+btnSound.getWidth();
	                        return true;
	                    } else if (event.getAction() == MotionEvent.ACTION_UP) {
	           	                    	//mod int pos=Math.round((currX-startX)*soundPosMax/150);
	                    	 //mod soundPos=soundPos+pos*soundPosMax/11;
		                       
	                    	   //mod int reaalPos=Math.round(soundPos);
		                       //mod setVolumeCtrl(getBaseContext(),btnSound,reaalPos);
		                       //modif (reaalPos==1) {reaalPos=0;}
		                      //mod if (reaalPos==11) {reaalPos=soundPosMax;}
		                       //mod mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, reaalPos, 0);
	                        return true;
	                    } else if(event.getAction() == MotionEvent.ACTION_OUTSIDE)
	                    {

	                        // Do some stuffs here
	                    }
	                    else if(event.getAction()==MotionEvent.ACTION_MOVE)
	                    {
	                       currX=event.getX();
	                       float step=Math.round(currX-startX);
	                       int pos=Math.round((startX+step)*soundPosMax/XMax);
	                       setVolumeCtrl(getBaseContext(),btnSound,pos);
                           mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, pos, 0);
	                    }

	                    return false;
	                }
	            });
			
			
	            bg = (ImageView) findViewById(R.id.bg);
	          	
	          	
	          	
	          	//loadTrack();    
	            
			playaudio(currentaudioIndex);
			play();
			progressLayout.setVisibility(View.INVISIBLE); 
			
		/*	SeekBar volControl = (SeekBar)findViewById(R.id.volumeProgressBar);
            volControl.setMax(soundPosMax);
            volControl.setProgress(soundPos);
            volControl.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {

        @Override
        public void onStopTrackingTouch(SeekBar arg0) {
         // TODO Auto-generated method stub

        }

        @Override
        public void onStartTrackingTouch(SeekBar arg0) {
         // TODO Auto-generated method stub
             
        }

        @Override
        public void onProgressChanged(SeekBar arg0, int arg1, boolean arg2) {
         // TODO Auto-generated method stub
        	setVolumeCtrl(getBaseContext(),btnSound,arg1);
        	mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, arg1, 0);
        }
       });*/
        //initialize(1);
    }
    
    public static void setVolumeCtrl(Context ctx,ImageButton bt,int pos){
    	//soundPos = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
		   int ps=Math.round(11*pos/soundPosMax)+1;
		    if (ps>11) {ps=11;} 
        if (ps<1) {ps=1;}
  	   int resId = ctx.getResources().getIdentifier("loudness_"+ps, "drawable", ctx.getPackageName());
		   bt.setImageResource(resId);
	   }
    
    public void play(){
    	if(isTuning){
			isTuning = false;
			btnPlay.setImageResource(R.drawable.play);
			track.pause();
		} else{
			isTuning = true;
			btnPlay.setImageResource(R.drawable.pause);
			playTrack();
		}
    }
    
    @Override
    public void onResume(){
    	super.onResume();
    	wakeLock.acquire();
    }
	
    @Override
	public void onPause(){
		super.onPause();
		wakeLock.release();
		if(track != null){
			if(track.isPlaying()){
				track.pause();
				isTuning = false;
				btnPlay.setImageResource(R.drawable.play);
			}
			if(isFinishing()){
				track.dispose();
				finish();
			}
		} else{
			if(isFinishing()){
				finish();
			}
		}
	}
    
    
    public static void callMenu(){
		if (controlsView.getVisibility()==View.VISIBLE){
			controlsView.startAnimation(slideUpOut);
			controlsView.setVisibility(View.GONE);
			titleView.startAnimation(slideTopOut);
			titleView.setVisibility(View.GONE);
		}else{
			controlsView.startAnimation(slideUpIn);
			controlsView.setVisibility(View.VISIBLE);
			titleView.startAnimation(slideTopIn);
			titleView.setVisibility(View.VISIBLE);
		}
	}
    
    //Generate a String Array that represents all of the files found
  /*  private String[] getTracks(){

    		if(type==1){
        		path = new File(new String(MEDIA_AUDIO_PATH));
    			String[] temp = path.list();
    			return temp;
    		} else{
    			//Toast.makeText(getBaseContext(), "SD Card is either mounted elsewhere or is unusable", Toast.LENGTH_LONG).show();
    		}
    	return null;
    }*/
    
    //Adds the playable files to the trackNames List
   /* private void addTracks(String[] temp){
    	if(temp != null){
			for(int i = 0; i < temp.length; i++){
				//Only accept files that have one of the extensions in the EXTENSIONS array
				if(trackChecker(temp[i])){
					trackNames.add(temp[i]);
					trackArtworks.add(temp[i].substring(0, temp[i].length()-4));
				}
			}
			//Toast.makeText(getBaseContext(), "Loaded " + Integer.toString(trackNames.size()) + " Tracks", Toast.LENGTH_SHORT).show();
		}
    }*/
    
    //Checks to make sure that the track to be loaded has a correct extenson
    private boolean trackChecker(String trackToTest){
    	for(int j = 0; j < EXTENSIONS.length; j++){
			if(trackToTest.contains(EXTENSIONS[j])){
				return true;
			}
		}
    	return false;
    }
    
    //Loads the track by calling loadMusic
    private void playaudio(int ix){
    	currentTrack=ix;
    	if(track != null){
    		track.dispose();
    	}
    	if(movieList.size() > 0){
    		track = loadMusic(type);
    		try {
				setImage(movieList.get(currentTrack).getThumbnailPath());
				
				String songTitle = movieList.get(currentTrack).getTitle();
	        	audioTitleLabel.setText(songTitle);//clearedFilename(songTitle));
				
				audioProgressBar.setProgress(0);
				audioProgressBar.setMax(100);
				
				// Updating progress bar
				updateProgressBar();	
				track.play();
				
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				//e.printStackTrace();
			}
    	}
    }
    
	//loads a Music instance using either a built in asset or an external resource
    private Music loadMusic(int type){
    	switch(type){
    	case 0:
    		try{
    			AssetFileDescriptor assetDescriptor = assets.openFd(movieList.get(currentTrack).getMoviePath());
    			return new Music(assetDescriptor,this);
    		} catch(IOException e){
    			e.printStackTrace();
    			//Toast.makeText(getBaseContext(), "Error Loading " + trackNames.get(currentTrack), Toast.LENGTH_LONG).show();
    		}
    		return null;
    	case 1:
    		try{
    			FileInputStream fis = new FileInputStream(new File(path, movieList.get(currentTrack).getMoviePath()));
    			FileDescriptor fileDescriptor = fis.getFD();
    			return new Music(fileDescriptor,this);
    		} catch(IOException e){
    			e.printStackTrace();
    			//Toast.makeText(getBaseContext(), "Error Loading " + trackNames.get(currentTrack), Toast.LENGTH_LONG).show();
    		}
    		return null;
    	default:
    		return null;
    	}
    }
     
  
    
    //Sets the background image to match the track currently playing or a default image
	private void setImage(String path) throws FileNotFoundException{//long album_id) throws FileNotFoundException {
		//Uri sArtworkUri = Uri.parse("content://media/external/audio/albumart");
		//Uri uri = ContentUris.withAppendedId(sArtworkUri, album_id);
		//--Uri uri=Uri.parse(path);
		//--bg.setImageURI(uri);
		bg.setTag(path);
		new LoadImageTask().execute(bg);
		//bg.setImageResource(R.drawable.ic_launcher);
	}

     
   
    
    private void setTrack(int direction){
    	if(direction == 0){
    		currentTrack--;
			if(currentTrack < 0){
				currentTrack = movieList.size()-1;
			}
    	} else if(direction == 1){
    		currentTrack++;
			if(currentTrack > movieList.size()-1){
				currentTrack = 0;
			}
    	}
    	
    }
    
    //Plays the Track
    private void playTrack(){
    	if(isTuning && track != null){
			track.play();
			//Toast.makeText(getBaseContext(), "Playing " + trackNames.get(currentTrack).substring(0, trackNames.get(currentTrack).length()-4), Toast.LENGTH_SHORT).show();
		}
    }
    
 
   /* @Override
    public boolean onTouchEvent(MotionEvent event) {

    	final int action = event.getAction();
        float y=event.getY();
		   if((action == MotionEvent.ACTION_UP) && (y<650) && (controlsView.getVisibility()==View.VISIBLE)) {
		       callMenu();
		   }else  if((action == MotionEvent.ACTION_UP )&&(controlsView.getVisibility()==View.GONE)) 
			   { callMenu();}
        return super.onTouchEvent(event);
    }*/
    
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        // or implement in activity or component. When your not assigning to a child component.
		final int action = event.getAction();
        float y=event.getY();
		   if((action == MotionEvent.ACTION_UP) && (y<550) && (controlsView.getVisibility()==View.VISIBLE)) {
		       callMenu();
		   }else  if((action == MotionEvent.ACTION_UP )&&(controlsView.getVisibility()==View.GONE)) 
			   { callMenu();}
        return myGestureListener.getDetector().onTouchEvent(event); 
    }
	
	
	public void updateProgressBar() {
        mHandler.postDelayed(mUpdateTimeTask, 100);        
    }	
	
	/**
	 * Background Runnable thread
	 * */
	private Runnable mUpdateTimeTask = new Runnable() {
		   public void run() {
			   long totalDuration = track.mediaPlayer.getDuration();
			   long currentDuration = track.mediaPlayer.getCurrentPosition();
			  
			   // Displaying Total Duration time
			   audioTotalDurationLabel.setText(""+utils.milliSecondsToTimer(totalDuration));
			   // Displaying time completed playing
			   audioCurrentDurationLabel.setText(""+utils.milliSecondsToTimer(currentDuration)+" /");
			   
			   // Updating progress bar
			   int progress = (int)(utils.getProgressPercentage(currentDuration, totalDuration));
			   //Log.d("Progress", ""+progress);
			  audioProgressBar.setProgress(progress);
			   
			   // Running this thread after 100 milliseconds
		       mHandler.postDelayed(this, 100);
		   }
		};
		
	/**
	 * 
	 * */
	@Override
	public void onProgressChanged(SeekBar seekBar, int progress, boolean fromTouch) {
		
	}

	/**
	 * When user starts moving the progress handler
	 * */
	@Override
	public void onStartTrackingTouch(SeekBar seekBar) {
		// remove message Handler from updating progress bar
		mHandler.removeCallbacks(mUpdateTimeTask);
    }
	
	/**
	 * When user stops moving the progress hanlder
	 * */
	@Override
    public void onStopTrackingTouch(SeekBar seekBar) {
		mHandler.removeCallbacks(mUpdateTimeTask);
		int totalDuration = track.mediaPlayer.getDuration();
		int currentPosition = utils.progressToTimer(seekBar.getProgress(), totalDuration);
		
		// forward or backward to certain seconds
		track.mediaPlayer.seekTo(currentPosition);
		
		// update timer progress again
		updateProgressBar();
    }

	/**
	 * On Song Playing completed
	 * if repeat is ON play same song again
	 * if shuffle is ON play random song
	 * */
	@Override
	public void onCompletion(MediaPlayer arg0) {
		
	
			// no repeat or shuffle ON - play next song
			if(currentaudioIndex < (movieList.size() - 1)){
				//playaudio(currentaudioIndex + 1);
				//currentaudioIndex = currentaudioIndex + 1;
			}else{
				// play first song
				//playaudio(0);
				//currentaudioIndex = 0;
			}
	}
	
	@Override
	public void onBackPressed() {
		mHandler.removeCallbacks(mUpdateTimeTask);
		Intent i = new Intent(getApplicationContext(), VidList.class);
		i.putExtra("menuOption",menuOption);
		startActivity(i);
		AudActivity.this.finish();//--
		AudActivity.this.overridePendingTransition(
				R.anim.slide_in_left, 
				R.anim.slide_out_right
	    		);
		//--finish();
	}
	
	@Override
	 public void onDestroy(){
	 super.onDestroy();
	 }
    
	public String clearedFilename(String filename){
    	String res=filename;
        int pos = res.lastIndexOf(".");
        if (pos > -1) res=res.substring(0, pos);
        res=res.replace("_LT","");
        res=res.replace("_EN","");
        pos = res.lastIndexOf("_");
        if (pos > -1) res=res.substring(pos+1, res.length());
    	return res;
    }
	
	class MyGestureDetector extends SimpleOnGestureListener {
        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
	    Intent intent = new Intent(AudActivity.this.getBaseContext(), AudActivity.class);
	    
	    intent.putExtra("menuOption", menuOption);
        intent.putParcelableArrayListExtra("movieList",movieList);
 
            if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH) {
            	
                return false;
            }
 
            // right to left swipe
            if(e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
            if(currentaudioIndex < (movieList.size() - 1)){
					currentaudioIndex = currentaudioIndex + 1;
				}else{
					currentaudioIndex = 0;
				}
        	intent.putExtra("listIndex", currentaudioIndex);
        	track.stop();
    		startActivity(intent);
    		AudActivity.this.finish();
    		AudActivity.this.overridePendingTransition(
			R.anim.slide_in_right,
			R.anim.slide_out_left
    		);
    		
    	    // right to left swipe
            }  else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
            	if(currentaudioIndex > 0){
					currentaudioIndex = currentaudioIndex - 1;
				}else{
					currentaudioIndex = movieList.size() - 1;
				}
        	intent.putExtra("listIndex", currentaudioIndex);
        	track.stop();
    		startActivity(intent);
    		AudActivity.this.finish();
    		AudActivity.this.overridePendingTransition(
			R.anim.slide_in_left, 
			R.anim.slide_out_right
    		);
    
    		
            }
 
            return false;
        }
 
        // It is necessary to return true from onDown for the onFling event to register
        @Override
        public boolean onDown(MotionEvent e) {
	        	return true;
        }
    }
	
	class MyGestureListener extends SimpleOnGestureListener implements OnTouchListener
    {
        Context context;
        GestureDetector gDetector;

        public MyGestureListener()
        {
            super();
        }

        public MyGestureListener(Context context) {
            this(context, null);
        }

        public MyGestureListener(Context context, GestureDetector gDetector) {

            if(gDetector == null)
                gDetector = new GestureDetector(context, this);

            this.context = context;
            this.gDetector = gDetector;
        }


        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {

        	Intent intent = new Intent(AudActivity.this.getBaseContext(), AudActivity.class);
    	    
    	    intent.putExtra("menuOption", menuOption);
            intent.putParcelableArrayListExtra("movieList",movieList);
     
                if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH) {
                    return false;
                }
     
                // right to left swipe
                if(e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
                	if(currentaudioIndex < (movieList.size() - 1)){
                		currentaudioIndex = currentaudioIndex + 1;
    				}else{
    					currentaudioIndex = 0;
    				}
                intent.putExtra("listIndex", currentaudioIndex);
                bg.setImageBitmap(null);
        		startActivity(intent);
        		//AudActivity.this.finish();
        		AudActivity.this.overridePendingTransition(
    			R.anim.slide_in_right,
    			R.anim.slide_out_left
        		);
        		android.os.Process.killProcess(android.os.Process.myPid());
        		//finish();
        	    // right to left swipe
                }  else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
                	if(currentaudioIndex > 0){
                		currentaudioIndex = currentaudioIndex - 1;
    				}else{
    					currentaudioIndex = movieList.size() - 1;
    				}
                intent.putExtra("listIndex", currentaudioIndex);
                bg.setImageBitmap(null);
        		startActivity(intent);
        		//AudActivity.this.finish();
        		AudActivity.this.overridePendingTransition(
    			R.anim.slide_in_left, 
    			R.anim.slide_out_right
        		);
           		android.os.Process.killProcess(android.os.Process.myPid());
        		//finish();
                }
     
            return super.onFling(e1, e2, velocityX, velocityY);
        }

        @Override
        public boolean onSingleTapConfirmed(MotionEvent e) {

            return super.onSingleTapConfirmed(e);
        }





        public boolean onTouch(View v, MotionEvent event) {

            // Within the MyGestureListener class you can now manage the event.getAction() codes.

            // Note that we are now calling the gesture Detectors onTouchEvent. And given we've set this class as the GestureDetectors listener 
            // the onFling, onSingleTap etc methods will be executed.
        	
        	return gDetector.onTouchEvent(event);
        }


        public GestureDetector getDetector()
        {
            return gDetector;
        }       
    }
	
}

class LoadImageTask extends AsyncTask<ImageView, Void, Bitmap> {

    ImageView imageView = null;

    @Override
    protected Bitmap doInBackground(ImageView... imageViews) {
        this.imageView = imageViews[0];
        return load_Image((String)imageView.getTag());
    }

    @Override
    protected void onPostExecute(Bitmap result) {
        imageView.setImageBitmap(result);
    }
    
   
    private Bitmap load_Image(String url) {

        Bitmap bmp =null;
        try{
        	Drawable drw=Drawable.createFromPath(url);
        	bmp = Bitmap.createBitmap(drw.getIntrinsicWidth(), drw.getIntrinsicHeight(), Config.ARGB_8888);
        	Canvas canvas = new Canvas(bmp); 
        	drw.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
            drw.draw(canvas);
        	//bmp=BitmapFactory.decodeFile(url); 
            if (null != bmp)
                return bmp;

            }catch(Exception e){}
        return bmp;
    }

}